package protocol;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.Random;

import udpSocket.layerOneClient;

public class layerTwoClient {

	public static void main(String args[]) throws Exception{

		layerOneClient physical = new layerOneClient();

		String data = "";
		String packet = "";
		String sequenceNumber = "0";

		boolean retry = false;

		BufferedReader inFromUser =
				new BufferedReader(new InputStreamReader(System.in));

		while(true){

			if(retry==false){
				System.out.print("Enter message to send: ");
				data = inFromUser.readLine();
				packet = sequenceNumber+data;
			}

			if(noise()==false)
				physical.clientSend(packet);

			System.out.println("Package sent: "+packet.substring(1, packet.length()));
			System.out.println("Sequence number: "+packet.charAt(0));

			String ack = "";

			try{
				
				ack = physical.clientReceive();
				System.out.println("Sequence number from Ack: "+ack);
				sequenceNumber = ""+ack.charAt(0);
				System.out.println("Package received!");
				retry = false;
				System.out.println(ack);
				
			}catch(SocketTimeoutException e){
				
				System.out.println("Package lost. Retrying...");
				retry = true;
				
			}

			
		}	

	}


public static boolean noise(){
	Random prob = new Random();
	boolean noise=false;
	int num = prob.nextInt(5);

	if(num==3){
		noise = true;
	}

	return noise;
}
}
